package com.qust.util;

import com.qust.agreement.EnDecAgreement;
import com.qust.agreement.Message;
import com.qust.agreement.message.EncryptionMessage;
import com.qust.agreement.message.TransmissionAlgorithmMessage;
import com.qust.encryptionAndDecryption.IEnDecryption;
import com.qust.encryptionAndDecryption.KeyPair;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.Promise;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.util.concurrent.ExecutionException;

public class NettyUtils {
    public static Channel generateChannel(String ip, int port, EventLoopGroup eventLoopGroup,MessageHandle messageHandle){
        Channel channel;
        Bootstrap bootstrap = new Bootstrap()
                .channel(NioSocketChannel.class)
                .group(eventLoopGroup)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        nioSocketChannel.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024 * 1024*1024, 16, 4, 0, 0));
                        nioSocketChannel.pipeline().addLast(new EnDecAgreement());
                        nioSocketChannel.pipeline().addLast(messageHandle);
                    }
                });
        ChannelFuture connect = null;
        try {
            connect = bootstrap.connect(ip,port).sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        channel = connect.channel();
        return channel;
    }
    @Getter
    @Setter
    @ChannelHandler.Sharable
    @AllArgsConstructor
    @NoArgsConstructor
    public static class MessageHandle extends ChannelInboundHandlerAdapter {
        private Promise<Message> resultPromise;
        
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            resultPromise.setSuccess((Message) msg);
            ctx.fireChannelRead(msg);
        }
    }

}
